// pages/transfer/tansferRecord/tansferRecord.js
import { getPartsList, disposeParts } from "../../../api/tansfer";
import dayjs from "dayjs";
import Notify from '@vant/weapp/notify/notify';
const {getLocation} = require('../../../utils/map.js')

const handleStatus = ['未处理', '已处理']

Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    handleStatus,
    timeStart: dayjs().format('YYYY-MM-DD 00:00:00'),
    timeEnd: dayjs().add(1, 'day').format('YYYY-MM-DD 00:00:00'),
    status: 0,
    transferList: [],
    showAbnormalDialog: false,
    currentItem: {},
    abnormalInfo: "",
    showStatus: false,
    abnormalType: '无货',
    onAbnormalDialogClose: {}
  },

  /**
   * 组件的方法列表
   */
  methods: {
    loadData() {
      const {timeStart, timeEnd} = this.data
      this.getPartsList()
      this.triggerEvent('getCountFromPart', {timeStart, timeEnd})
    },
    // 获取列表
    getPartsList() {
      const { timeStart, timeEnd, status } = this.data
      getPartsList({
        timeStart: timeStart,
        timeEnd: timeEnd,
        status: status
      })
        .then(res => {
          if (res.data && res.data.result) {
            this.setData({
              transferList: res.data.result.content && res.data.result.content.map(item => {
                return {
                  ...item,
                  deliveryStartTime: item.deliveryStartTime ? dayjs(item.deliveryStartTime).format('YYYY-MM-DD hh:mm:ss') : '-',
                  deliveryEndTime: item.deliveryEndTime ? dayjs(item.deliveryEndTime).format('YYYY-MM-DD hh:mm:ss') : '-',
                }
              }),
            });
          } else {
            this.setData({
              transferList: [],
            });
          }
        })
        .finally(() => {
        });
    },
    handledDateRange(event) {
      const {start, end} = event.detail
      this.setData({
        timeStart: start,
        timeEnd: end,
      })
      console.log(start, end)
    },
    onSubmitAbnormal(event) {
      const {item} = event.currentTarget.dataset
      this.setData({
        showAbnormalDialog: true,
        currentItem: item
      })
    },
    // 异常提交
    async submitAbnormal() {
      const { abnormalInfo, currentItem, abnormalType } = this.data
      
      this.disposeParts({
        item: currentItem,
        remark: abnormalType == '其他' ? abnormalInfo : abnormalType
      }).then(() => {
        this.loadData()
      })
    },

    // 异常信息关闭前
    handleAbnormalDialogClose(action) {
      return new Promise(resolve => {
        const { abnormalInfo, abnormalType } = this.data
        if (action === 'confirm') {
          if (!abnormalInfo && abnormalType === '其他') {
            Notify({
              message: '请填写异常信息！',
              type: 'danger',
              duration: 3000,
              zIndex: 3000
            })
            resolve(false)
            return;
          } else {
            this.submitAbnormal()
          }
        }
        resolve(true)
      })
    },

    disposeParts({item, remark}) {
      return disposeParts({
        id: item.id,
        orderId: item.orderId,
        orderDetailId: item.orderDetailId,
        remark: remark,
        goodsName: item.goodsName,
      })
        .then(res => {
          if (res.data.code == 200) {
            Notify({
              message: '提交成功',
              type: 'success'
            })
          } else {
            Notify({
              message: res.data.msg || '失败，请重试',
              type: 'danger'
            })
          }
        })
        .catch(err => {
          Notify({
            message: err.msg || '失败，请重试',
            type: 'danger'
          })
        });
    },
    // 带走
    handleTake(event) {
      const {item} = event.currentTarget.dataset
      wx.showModal({
        title: '提示',
        content: `请确认是否带走【${item.goodsName}-${item.xmbzNo}】?`,
        success: (res) => {
          if (res.confirm) {
            this.disposeParts({
              item,
              remark: `${wx.getStorageSync('name')}: 带走`,
            }).then(() => {
              this.loadData()
            })
          }
        }
      })
    },
    onShowStatus() {
      this.setData({showStatus: true})
    },
    onStatusConfirm(event) {
      const { picker, value, index } = event.detail;
      this.setData({showStatus: false, status: index})
    },
    onStatusCancel() {
      this.setData({showStatus: false})
    },
    // 异常类型变化
    onErrorTypeChange(event) {
      this.setData({abnormalType: event.detail})
    },
    // 页面相关事件处理函数
    onPullDownRefresh() {
      this.loadData()
      wx.stopPullDownRefresh()
    },
  },

  lifetimes: {
    attached: function() {
      // 在组件实例进入页面节点树时执行
      const {timeStart, timeEnd} = this.data
      const dateRangeCom = this.selectComponent('#dateRange')
      dateRangeCom.setDefaultDate([timeStart, timeEnd])
      this.getPartsList()
      this.setData({
        onAbnormalDialogClose:  (action) => {return this.  handleAbnormalDialogClose(action)}
      })
    },
    detached: function() {
      // 在组件实例被从页面节点树移除时执行
    },
  },
})
